package com.fenghongzhang.lib_base.core

import android.os.Bundle
import android.view.LayoutInflater
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.viewbinding.ViewBinding
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

abstract class BaseActivity<VB : ViewBinding, MV : ViewModel>(
    private val bindingInflater: (LayoutInflater) -> VB
) : AppCompatActivity() {

    protected lateinit var binding: VB
    protected abstract val viewModel: MV

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        println("onCreate")
        binding = bindingInflater.invoke(layoutInflater)
        setContentView(binding.root)
        initView()
        initData()
    }

    abstract fun initView()
    abstract fun initData()

    //21, 收集vm返回的流
    protected open fun <S> collectState(stateFlow: StateFlow<S>, collector: (S) -> Unit) {
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED){
                stateFlow.collectLatest(collector)
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (this::binding.isInitialized) {
            val bindingClass = binding::class.java
            if (bindingClass.name.endsWith("Binding")) {
                val unbindMethod = bindingClass.getMethod("unbind")
                unbindMethod.invoke(binding)
            }
        }
    }
}